import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { nanoid } from 'nanoid';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';

export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const trip = await prisma.trip.findUnique({
      where: { id: params.id },
      select: { 
        isPublic: true,
        isOfficial: true,
        userId: true, 
        shareCode: true 
      }
    });

    if (!trip) {
      return NextResponse.json({ error: '行程不存在' }, { status: 404 });
    }

    // 如果是公开或官方行程，允许任何人分享
    if (!trip.isPublic && !trip.isOfficial) {
      const session = await getServerSession(authOptions);
      if (!session?.user?.id || trip.userId !== session.user.id) {
        return NextResponse.json({ error: '无权限分享此行程' }, { status: 403 });
      }
    }

    // 如果已有分享码，直接返回
    if (trip.shareCode) {
      return NextResponse.json({ shareCode: trip.shareCode });
    }

    // 生成新的分享码
    const shareCode = nanoid(10);
    const updatedTrip = await prisma.trip.update({
      where: { id: params.id },
      data: { shareCode }
    });

    return NextResponse.json({ shareCode: updatedTrip.shareCode });
  } catch (error) {
    console.error('Share trip error:', error);
    return NextResponse.json(
      { error: '分享失败' },
      { status: 500 }
    );
  }
} 